import { splitMenuLevel, findMenu } from '@/utils/menusUtil'
import Cookies from 'js-cookie'
const menus = {
  state: {
    sidebar: {
      opened: !+Cookies.get('sidebarStatus'),
      hid: false
    },
    menus: {},
    // menuActiveIndex:Cookies.get('menuActiveIndex'),
    sidebarMenus: [],
    sidebarMenusIndex: '',
    curMenu: null
  },
  mutations: {
    TOGGLE_SIDEBAR: state => {
      if (state.sidebar.opened) {
        Cookies.set('sidebarStatus', 1)
      } else {
        Cookies.set('sidebarStatus', 0)
      }
      state.sidebar.opened = !state.sidebar.opened
    },
    CLOSE_SIDEBAR: (state) => {
      Cookies.set('sidebarStatus', 0)
      state.sidebar.opened = false
    },
    OPEN_SIDEBAR: (state) => {
      if (!+Cookies.get('sidebarStatus')) {
        state.sidebar.opened = true
      }
    },
    REFRESH_CUR_MENU: (state, router) => {
      if (Object.keys(router.meta).length === 0) {
        // 没有meta信息, 直接返回
        state.sidebar.hid = true
        return -1
      }

      const curMenu = splitMenuLevel(router.meta)
      state.sidebar.hid = !(curMenu.length >= 2)
      if (!state.curMenu || curMenu[0].code !== state.curMenu[0].code) {
        state.sidebarMenus = findMenu(state.menus, curMenu[0].code).children || []
        state.sidebarMenusIndex = curMenu[curMenu.length - 1].code
      } else {
        state.sidebarMenusIndex = curMenu[curMenu.length - 1].code
      }
      state.curMenu = curMenu
    },

    RELOAD_MENUS: (state, menus) => {
      state.menus = menus
    }
  },

  actions: {
    ToggleSideBar: ({ commit }) => {
      commit('TOGGLE_SIDEBAR')
    },
    CloseSideBar({ commit }) {
      commit('CLOSE_SIDEBAR')
    },
    OpenSideBar({ commit }) {
      commit('OPEN_SIDEBAR')
    },
    ToggleDevice({ commit }, device) {
      commit('TOGGLE_DEVICE', device)
    },
    ReloadMenus: ({ commit }, menus) => {
      commit('RELOAD_MENUS', menus)
    },
    RefreshCurMenu: ({ commit }, router) => {
      commit('REFRESH_CUR_MENU', router)
    }
  }
}

export default menus
